var key = "3edf0f777c932b22964f846a9cf43a51";
var map;
var baseLayers;
var overlays;
var popLayer;
var rchDatas;
var currentTime = "2014年2月";
var paramShow="ALL";
var clickMarker;
var reachHotLineLayer;
var taburl;

/**
 * 添加底图
 */
function addBaselayers(){
    var imgMap = L.tileLayer('http://t0.tianditu.gov.cn/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=' + key, {
        maxZoom: 19,
        minZoom: 5,
        zoomOffset: 1
    });
    var ciaMap = L.tileLayer('http://t0.tianditu.gov.cn/cia_c/wmts?layer=cia&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=' + key, {
        maxZoom: 19,
        minZoom: 5,
        zoomOffset: 1
    });
    var terMap = L.tileLayer('http://t0.tianditu.gov.cn/ter_c/wmts?layer=ter&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=' + key, {
        maxZoom: 19,
        minZoom: 5,
        zoomOffset: 1
    });
    var ctaMap = L.tileLayer('http://t0.tianditu.gov.cn/cta_c/wmts?layer=cta&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=' + key, {
        maxZoom: 19,
        minZoom: 5,
        zoomOffset: 1
    });
    var vecMap = L.tileLayer('http://t0.tianditu.gov.cn/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=' + key, {
        maxZoom: 19,
        minZoom: 5,
        zoomOffset: 1
    });
    var cvaMap = L.tileLayer('http://t0.tianditu.gov.cn/cva_c/wmts?layer=cva&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=' + key, {
        maxZoom: 19,
        minZoom: 5,
        zoomOffset: 1
    });
    baseLayers = {
        "卫星底图": L.layerGroup([imgMap, ciaMap]),
        "矢量底图": L.layerGroup([vecMap, cvaMap]),
        "地形底图": L.layerGroup([terMap, ctaMap]).addTo(map)
    };
}

/**
 * 添加叠加图层
 */
function addOverlays(){
    var iconObservation = L.icon({
        iconUrl: 'images/Point_2.png',
        iconSize: [32, 32]
    });

    var observationLayer = new L.GeoJSON.AJAX("./datas/esri/Observation.json",{
        middleware: function(data){
            return esri2geo.toGeoJSON(data);
        },
        pointToLayer: function (feature, latlng) {
            return L.marker(latlng, {icon: iconObservation});
        },
        onEachFeature: function(feature, layer){
            var labelStr = feature.properties["监测站点"];
            layer.bindTooltip(labelStr);
        }
    }).addTo(map);
    observationLayer.on('click', markerClickedEvent);

    var icon3D_1 = L.icon({
        iconUrl: 'images/point_3d1.png',
        iconSize: [32, 32]
    });
    var icon3D_2 = L.icon({
        iconUrl: 'images/point_3d2.png',
        iconSize: [32, 32]
    });
    var icon3D_3 = L.icon({
        iconUrl: 'images/point_3d3.png',
        iconSize: [32, 32]
    });
    var icon3D_4 = L.icon({
        iconUrl: 'images/point_3d4.png',
        iconSize: [32, 32]
    });
    var point3DLayer = new L.GeoJSON.AJAX("datas/3dPoint.json",{
        pointToLayer: function (feature, latlng) {
            var type = feature.properties.type;
            var icon3D = null;
            if (type == "1"){
                icon3D = icon3D_1;
            }else if (type == "2"){
                icon3D = icon3D_2;
            }else if (type == "3"){
                icon3D = icon3D_3;
            }else{
                icon3D = icon3D_4;
            }
            return L.marker(latlng, {icon: icon3D});
        },
        onEachFeature: function(feature, layer){
            var labelStr = feature.properties["name"];
            layer.bindTooltip(labelStr);
        }
    }).addTo(map);
    point3DLayer.on('click', show3DModel);

    var basinLayer = new L.GeoJSON.AJAX("./datas/esri/Basin.json",{
        middleware: function(data){
            return esri2geo.toGeoJSON(data);
        },
        style: {
            fillColor: '#ffffff',
            fillOpacity: 0,
            color: '#ff0000',
            weight: 8
        }
    }).addTo(map);
    var watershedLayer = new L.GeoJSON.AJAX("datas/esri/Watershed.json", {
        middleware: function(data){
            return esri2geo.toGeoJSON(data);
        },
        style: {
            fillColor: '#DDEEDB',
            fillOpacity: 0.9,
            color: '#FEA0E9',
            weight: 1
        }
    }).addTo(map);

    var options = {
        opacity: 1,
        colorScale: L.colors['black - white'],
        autoScale: false,
        scaleMin: 0,
        scaleMax: 1435
    };
    var dem = new L.BilDem("./datas/dem.zip", options);

    overlays.observation = observationLayer;
    overlays.point3D = point3DLayer;
    overlays.basin = basinLayer;
    overlays.watershed = watershedLayer;
    overlays.dem = dem;
    addReachHotLineLayer();
}

function addReachHotLineLayer() {
    if (!reachHotLineLayer){
        reachHotLineLayer = L.layerGroup([]).addTo(map);
        overlays.reachhot = reachHotLineLayer;

        var reachLayer = new L.GeoJSON.AJAX("./datas/esri/Reach.json", {
            middleware: function(data){
                reachData = esri2geo.toGeoJSON(data);
                var rchValues = getRchByTime(currentTime);

                reDrawRechHotLineLayer(reachData, rchValues);
            }
        });
    }else{
        reachHotLineLayer.clearLayers();
        var rchValues = getRchByTime(currentTime);
        reDrawRechHotLineLayer(reachData, rchValues);
    }
}

function reDrawRechHotLineLayer(geoJSONData, rchValues){
    for (var i=0; i<geoJSONData.features.length; i++){
        var tempLinePoint = geoJSONData.features[i].geometry.coordinates;
        var tempCoor = [];
        var id = geoJSONData.features[i].properties.Subbasin;
        var points = getReachPoint(id);
        var startVal = 0;
        var endVal = 0;

        if (paramShow == "ALL"){
            if (points[0] != "-1") {
                var tempVal1 = getParamClass(getRchById(points[0], rchValues, "NH4"), "NH4");
                var tempVal2 = getParamClass(getRchById(points[0], rchValues, "P"), "P");
                startVal = (tempVal1 > tempVal2)? tempVal1 : tempVal2;
            }
            var tempVal3 = getParamClass(getRchById(points[1], rchValues, "NH4"), "NH4");
            var tempVal4 = getParamClass(getRchById(points[1], rchValues, "P"), "P");
            endVal = (tempVal3 > tempVal4)? tempVal3 : tempVal4;
        }else {
            if (points[0] != "-1") {
                startVal = getParamClass(getRchById(points[0], rchValues, paramShow), paramShow);
            }
            endVal = getParamClass(getRchById(points[1], rchValues, paramShow), paramShow);
        }
        var tempVal = endVal-startVal;

        for (var j=0; j<tempLinePoint.length; j++){
            var value = (j/tempLinePoint.length)*tempVal + startVal;
            tempCoor[j] = [tempLinePoint[j][1], tempLinePoint[j][0], value];
        }

        reachHotLineLayer.addLayer(L.hotline(tempCoor, {
            min: 0,
            max: 5,
            palette: {
                0.0: '#240fe0',
                0.2: '#5976fa',
                0.4: '#f5e612',
                0.6: '#ee7b38',
                0.8: '#f2000a',
                1.0: '#6f0c8d'
            },
            weight: 5,
            outlineColor: '#000000',
            outlineWidth: 0
        }));
    }
}

/**
 * 点点击事件
 * @param e 点击事件对象
 */
function markerClickedEvent(e) {
    if (e.sourceTarget && e.sourceTarget.feature && e.sourceTarget.feature.properties){
        var feature = e.sourceTarget.feature;
        $(".header .title").html(feature.properties["监测站点"]);
        showChart(true);
        loadChartData(feature);
        var pulsingIcon = L.icon.pulse({iconSize:[20,20],color:'red'});
        clickMarker = L.marker(e.latlng,{icon: pulsingIcon}).addTo(map);
    }
}

// 加载图表
function loadChartData(feature) {
    if (feature.properties["GRID_CODE"] == 4){
        buildChartFlow198089("chart1");
        $("#chart1").show();
    }else {
        $("#chart1").hide();
    }
    if (clickMarker){
        map.removeLayer(clickMarker);
        clickMarker = null;
    }
    $.getJSON("datas/chart/flow" + feature.properties["GRID_CODE"] + ".json", function(data){
        buildChartFlow(data, "chart2");
    });
    $.getJSON("datas/chart/NH4_" + feature.properties["GRID_CODE"] + ".json", function(data){
        buildChartNH4(data, "chart3");
    });
    $.getJSON("datas/chart/P_" + feature.properties["GRID_CODE"] + ".json", function(data){
        buildChartP(data, "chart4");
    });
    taburl = feature.properties["tab"];
}

// 显示图表
function showChart(flag){
    if (flag){
        $("#mapPanel").width($(window).width() - 600);
        $("#rightPanel").show();
        $("#timePlay").css("width", "55%");
    }else{
        $("#mapPanel").css("width", "100%");
        $("#rightPanel").hide();
        $("#timePlay").css("width", "80%");
        if (clickMarker){
            map.removeLayer(clickMarker);
            clickMarker = null;
        }
    }
    $(".chartPanel").height($(window).height() - 70);
}

//显示三维模型
function show3DModel(e){
    if (e.sourceTarget && e.sourceTarget.feature && e.sourceTarget.feature.properties){
        var prop = e.sourceTarget.feature.properties;

        popLayer.open({
            title: prop["name"]
            ,type: 2
            ,content: prop["url"],
            area:['80%', '80%']
        });

    }
}

// 更新河流图层
function updateReachHotLayer(time, param) {
    if (overlays.reachhot){
        // 清空旧涂层
        overlays.reachhot.clearLayers();

        currentTime = time;
        paramShow = param;
        addReachHotLineLayer();
    }
}

// 通过时间获取水质数据
function getRchByTime(time){
    if (rchDatas){
        for (var i=0; i<rchDatas.length; i++){
            var item = rchDatas[i];
            if (item.time == time){
                return rchDatas[i].data;
            }
        }
    }
}

// 通过流域ID获取水质数据
function getRchById(id, datas, param){
    for (var i=0; i<datas.length; i++){
        var item = datas[i];
        if (item.id == id){
            return item[param];
        }
    }
}

// 河流段与检测值映射
function getReachPoint(id){
    var mappingArray = [
        ["9", "10"],
        ["-1", "7"],
        ["7", "8"],
        ["8", "9"],
        ["-1", "7"],
        ["6", "8"],
        ["5", "6"],
        ["-1", "5"],
        ["4", "5"],
        ["-1", "4"],
        ["3", "4"],
        ["2", "3"],
        ["1", "3"],
        ["-1", "2"],
        ["-1", "1"]
    ];
    return mappingArray[id-1];
}

function getParamClass(value, paramShow){
    if (value <= 0.15 && paramShow == "NH4" || value <= 0.02 && paramShow == "P"){
        return 0;
    }
    if (value <= 0.5 && paramShow == "NH4" || value <= 0.1 && paramShow == "P"){
        return 1;
    }
    if (value <= 1 && paramShow == "NH4" || value <= 0.2 && paramShow == "P"){
        return 2;
    }
    if (value <= 1.5 && paramShow == "NH4" || value <= 0.3 && paramShow == "P"){
        return 3;
    }
    if (value <= 2 && paramShow == "NH4" || value <= 0.4 && paramShow == "P"){
        return 4;
    }

    return 5;
}


$(function(){
    $.getJSON("datas/chart/rch.json", function (data) {
       rchDatas = data;
    });
    layui.use('layer', function(){
        popLayer = layui.layer;
    });
    map = L.map("mapPanel", {
        crs: L.CRS.EPSG4326,
        center: [29.495, 120.620],
        zoom: 10,
        zoomControl: false,
        dragging: true,
        zoomSnap: 1,
        zoomDelta: 1
    });
    overlays = {}
    map.createPane("pane450").style.zIndex = 450;
    addBaselayers();
    addOverlays();

    L.control.layers(baseLayers, overlays).addTo(map);

    var timeplay = new TimePlay({
        speed: 1000,//播放速度
        startDate: "201101",//开始日期
        endDate: "201812",//结束日期
        timeUnitControl: true,//是否显示时/天切换控件
        onClickChangeEnd: function(){//点击后回调
            //获取点击的时间
            var hour = timeplay.curr_day.hour,//小时
                day  = timeplay.curr_day.day,//日
                mon  = timeplay.curr_day.mon,//月
                year = timeplay.curr_day.year;//年
            updateReachHotLayer(year+"年"+mon+"月", paramShow);
        },
        onAnimateEnd: function(){//时间轴动画每次结束回调
            var hour = timeplay.curr_day.hour,//小时
                day  = timeplay.curr_day.day,//日
                mon  = timeplay.curr_day.mon,//月
                year = timeplay.curr_day.year;//年
            updateReachHotLayer(year+"年"+mon+"月", paramShow);
        },
        paramChangeEnd: function (index) {
            if (index == 0){
                paramShow = "ALL";
            }else if (index == 1){
                paramShow = "NH4";
            }else{
                paramShow = "P";
            }
            updateReachHotLayer(currentTime, paramShow);
        }
    });
});
